package edu.tongji.engine.taskmgr;

import java.util.Date;

import edu.tongji.engine.common.Log;
import edu.tongji.engine.db.dao.DAOFactory;
import edu.tongji.engine.db.dao.INodeDao;
import edu.tongji.engine.db.dao.ITaskDao;
import edu.tongji.engine.db.pojo.Task;
import edu.tongji.engine.def.ActivityNode;
import edu.tongji.engine.exe.Token;
import edu.tongji.engine.plugin.mail.MailNotify;
import edu.tongji.engine.service.TokenService;

public class TaskMgrService {
	
	private ITaskDao dao;
	private INodeDao nodeDao;
	private TokenService tokenService;
	
	public TaskMgrService(){
		dao = DAOFactory.createTaskDao();
		nodeDao = DAOFactory.createNodeDao();
		tokenService = new TokenService();
	}

	public boolean createTask(ActivityNode node, Token token){
		//create a task
		try{
			Task task = new Task();
			Date date = new Date();
			task.setStartTime(date);
			task.setState("created");
			task.setToken(token);
			task.setActor(node.getActor());
			node.getActor().getTasks().add(task);
			nodeDao.saveNode(node);
			dao.saveTask(task);
			int mail = node.getMail();
			System.out.println("mail sned "+mail);
			if(mail==1)
				this.sendNewTaskEmail(task.getActor().getEmail(), task.getId());
			
			return true;
		}catch(Exception e){
			e.printStackTrace();
			Log.getLoger().loger.error("EnterEvent Error", e);
			return false;
		}
	}
	
	public boolean endTask(Task task){
		try{
			//change task state
			if(task.getState().equals("created")){
				task.setState("finished");
				Date date = new Date();
				task.setEndTime(date);
				tokenService.next(task.getToken());
				dao.saveTask(task);
				
				return true;
			}else{
				Log.getLoger().loger.error("End task Error,Task has finished");
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.getLoger().loger.error("End task Error", e);
			return false;
		}finally{
			
			System.out.println("TaskMgrService end task");
		}
	}
	
	public boolean sendNewTaskEmail(String email, Long taskId){
		try{
			MailNotify mail = new MailNotify();
			String[] to = {email};
			mail.sendCreateTaskMail(to,taskId);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			Log.getLoger().loger.error("Send Email Error", e);
			return false;
		}
	}
}
